<script setup lang="ts">
import { question_answer } from "./utils/hook";

import { ref, computed, nextTick, onMounted } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  delay,
  subBefore,
  deviceDetection,
  useResizeObserver
} from "@pureadmin/utils";

// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Close from "@iconify-icons/ep/close";
import Check from "@iconify-icons/ep/check";
import Upload from "@iconify-icons/ep/upload";
import AddLocation from "@iconify-icons/ep/add-location";

import { useAdminHooks } from "@/views/common/admin";

import { classifyFormat } from "@/views/formats";
const { classifyMenuOptions: typesMenuOptions } = classifyFormat("classify");
const { classifyMenuOptions: businessMenuOptions } = classifyFormat("business");

const { adminList, isSuperAdmin } = useAdminHooks();
defineOptions({
  name: "craft"
});

const iconClass = computed(() => {
  return [
    "w-[22px]",
    "h-[22px]",
    "flex",
    "justify-center",
    "items-center",
    "outline-none",
    "rounded-[4px]",
    "cursor-pointer",
    "transition-colors",
    "hover:bg-[#0000000f]",
    "dark:hover:bg-[#ffffff1f]",
    "dark:hover:text-[#ffffffd9]"
  ];
});

const treeRef = ref();
const formRef = ref();
const tableRef = ref();
const contentRef = ref();
const treeHeight = ref();

const {
  titleMenu,
  form,
  isShow,
  loading,
  columns,
  rowStyle,
  dataList,
  pagination,
  onSearch,
  resetForm,
  openDialog,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleDelete,
  selectedNum,
  onSelectionCancel,
  onbatchDel,
  handleImport,
  handleImportRecord,
  onGenerateArticle,
  handleGenerateArticle
} = question_answer(tableRef);

const searchTypeChange = () => {
  form.search = "";
};

onMounted(() => {
  useResizeObserver(contentRef, async () => {
    await nextTick();
    delay(60).then(() => {
      treeHeight.value = parseFloat(
        subBefore(tableRef.value.getTableDoms().tableWrapper.style.height, "px")
      );
    });
  });
});
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="搜索类型" prop="search_type" class="!w-[230px]">
        <el-select v-model="form.search_type" @change="searchTypeChange">
          <el-option key="" label="请选择搜索类型" value="" />
          <el-option
            key="type_classify_id"
            label="类型分类"
            value="type_classify_id"
          />
          <el-option
            key="business_classify_id"
            label="业务分类"
            value="business_classify_id"
          />
          <el-option key="question" label="问题" value="question" />
          <el-option key="answer" label="答案" value="answer" />
          <el-option
            key="generation_count"
            label="生成文章次数"
            value="generation_count"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索内容" prop="search">
        <el-input
          v-if="
            form.search_type === 'question' || form.search_type === 'answer'
          "
          v-model="form.search"
          placeholder="请输入搜索内容"
          clearable
        />

        <div
          v-else-if="form.search_type === 'generation_count'"
          class="flex items-center"
        >
          <el-input-number
            v-model="form.searchMin"
            placeholder="最小值"
            :min="0"
            class="!w-[120px]"
          />
          <span class="mx-2">-</span>
          <el-input-number
            v-model="form.searchMax"
            placeholder="最大值"
            :min="0"
            class="!w-[120px]"
          />
        </div>

        <el-cascader
          v-else-if="form.search_type === 'business_classify_id'"
          v-model="form.search"
          class="w-full"
          :options="businessMenuOptions"
          :props="{
            value: 'id',
            label: 'title',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          filterable
          placeholder="请选择上级菜单"
        >
          <template #default="{ node, data }">
            <span>{{ data.title }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
        <el-cascader
          v-else-if="form.search_type === 'type_classify_id'"
          v-model="form.search"
          class="w-full"
          :options="typesMenuOptions"
          :props="{
            value: 'id',
            label: 'title',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          filterable
          placeholder="请选择上级菜单"
        >
          <template #default="{ node, data }">
            <span>{{ data.title }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
        <el-select v-else v-model="form.search" class="!w-[160px]">
          <el-option value="请选择搜索类型" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div
      ref="contentRef"
      :class="['flex', deviceDetection() ? 'flex-wrap' : '']"
    >
      <PureTableBar
        :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']"
        style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)"
        :title="titleMenu + '管理'"
        :columns="columns"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog()"
          >
            新增
          </el-button>
          <el-button type="primary" @click="handleImport"> 导入 </el-button>
          <el-button type="primary" @click="handleImportRecord">
            导入记录
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <div
            v-if="selectedNum > 0"
            v-motion-fade
            class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
          >
            <div class="flex-auto">
              <span
                style="font-size: var(--el-font-size-base)"
                class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
              >
                已选 {{ selectedNum }} 项
              </span>
              <el-button type="primary" text @click="onSelectionCancel">
                取消选择
              </el-button>
            </div>

            <el-popconfirm title="是否确认删除?" @confirm="onbatchDel">
              <template #reference>
                <el-button type="danger" text class="mr-1">
                  批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <pure-table
            ref="tableRef"
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :row-style="rowStyle"
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="pagination"
            :paginationSmall="size === 'small' ? true : false"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('修改', row)"
              >
                修改
              </el-button>
              <el-popconfirm
                :title="`是否确认删除${titleMenu}：${row.question}`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="danger"
                    :size="size"
                    :icon="useRenderIcon(Delete)"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
